<template>
   <ContentWrap>
    <div v-loading="formLoading" class="bg">
      <!-- 10-编辑中、20-待检验、30-已检验、40-已作废-->
     <div class="btns routeHeader mb-5px" ref="topBoxRef">
      <el-button
        @click="submitForm('save')"
        :loading="formLoading"
        type="primary"
        v-hasPermi="['quality:mgmt-defective-product-registration:save']"
        v-if="(formData.dictExceptionRegistrationStatus==10 && !viewStatus) || query.type=='create' "
      >
        保存
      </el-button>
      <el-button
        type="primary"
        @click="submitForm('commit')"
        :loading="formLoading"
        v-hasPermi="['quality:mgmt-defective-product-registration:commit']"
        v-if="(formData.dictExceptionRegistrationStatus==10 && !viewStatus) || query.type=='create'"
      >
        提交
      </el-button>
      <el-button
        type="danger"
        @click="submitForm('cancel')"
        :loading="formLoading"
        v-hasPermi="['quality:mgmt-defective-product-registration:cancel']"
        v-if="formData.dictExceptionRegistrationStatus==10 && !viewStatus"
      >
        作废
      </el-button>
      <el-button
        type="danger"
        @click="submitForm('withdraw')"
        :loading="formLoading"
        v-hasPermi="['quality:mgmt-defective-product-registration:withdraw']"
        v-if="formData.dictExceptionRegistrationStatus==20 && !viewStatus"
      >
        撤回
      </el-button>
      <el-button @click="goBack"> 关闭 </el-button>
     </div>
      <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
    <el-form-item label="检验类型" prop="dictInspectType">
        <el-select 
        v-model="formData.dictInspectType" 
        placeholder="请选择检验类型"
        :disabled="formData.dictExceptionRegistrationStatus==20 || viewStatus " >
          <el-option
            v-for="dict in getIntDictOptions('dict_inspect_type')"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="检验任务号" prop="checkTaskNumber">
        <el-input v-model="formData.checkTaskNumber" placeholder="" disabled />
      </el-form-item>
      <el-form-item label="产品编号" prop="productNumber">
        <el-input v-model="formData.productNumber" placeholder="" disabled />
      </el-form-item>
      <el-form-item label="部件编号" prop="partNumber">
        <el-input v-model="formData.partNumber" placeholder="请选择部件编号" readonly :disabled="formData.dictExceptionRegistrationStatus==20 || viewStatus">
          <template #append>
            <el-button :icon="Search" @click="openPartNumberForm()"/>
          </template>
          </el-input>
      </el-form-item>
      <el-form-item label="部件名称" prop="partName">
        <el-input v-model="formData.partName" placeholder="" disabled/>
      </el-form-item>
      <el-form-item label="图纸图号" prop="drawingNumber">
        <el-input v-model="formData.drawingNumber" placeholder="" disabled/>
      </el-form-item>
      <el-form-item label="异常数量" prop="exceptionQuantity" >
        <el-input 
        v-model.numbe="formData.exceptionQuantity" 
        placeholder="请输入异常数量" 
        @input="validateInput"
        :disabled="formData.dictExceptionRegistrationStatus==20 || viewStatus"/>
      </el-form-item>
      <!--字段 -->
      <el-form-item label="客户名称" prop="customerName">
        <el-input v-model="formData.customerName" placeholder="" disabled/>
      </el-form-item>
      <!--  -->
      <el-form-item label="单位" prop="partUnit">
        <el-input v-model="formData.partUnit" placeholder="" disabled/>
      </el-form-item>
      <el-form-item label="描述" prop="description">
        <el-input 
        v-model="formData.description" 
        type="textarea" 
        placeholder="请输入描述"
        maxlength="200" 
        show-word-limit
        style="width:500px"
        :disabled="formData.dictExceptionRegistrationStatus==20 || viewStatus"/>
      </el-form-item>
      <el-form-item label="最终结论" prop="dictFinalConclusion">
        <el-select v-model="formData.dictFinalConclusion" placeholder="" disabled>
          <el-option
            v-for="dict in getIntDictOptions('dict_final_conclusion')"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="检验说明" prop="inspectionNotes">
        <el-input 
        v-model="formData.inspectionNotes" 
        type="textarea" 
        placeholder=""
        maxlength="200" 
        show-word-limit
        style="width:500px"
        disabled/>
      </el-form-item>
    </el-form>
     </div>
  <PartNumberForm  ref="partNumberFormRef" @getPartNumber="getPartNumber"/>
</ContentWrap>
</template>
<script setup>
import { getIntDictOptions } from '@/utils/dict'
import * as MgmtDefectiveProductRegistrationApi from '@/api/quality/qualitycontrol/mgmtDefectiveProductRegistration'
import { useTagsViewStore } from '@/store/modules/tagsView'
import { Search } from '@element-plus/icons-vue'
import PartNumberForm from './partNumberForm.vue'
const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗
const dialogVisible = ref(false) // 弹窗的是否展示
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const topBoxRef = ref()
const formData = ref({
id:undefined,
dictInspectType:undefined,
checkTaskNumber:undefined,
productNumber:undefined,
partNumber:undefined,
partName:undefined,
drawingNumber:undefined,
exceptionQuantity:undefined,
description:undefined,
dictFinalConclusion:undefined,
inspectionNotes:undefined,
customerName:undefined,
partUnit:undefined
})
const formRules = reactive({
  dictInspectType: [{ required: true, message: '检验类型不能为空', trigger: 'change' }],
  partNumber: [{ required: true, message: '部件编号不能为空', trigger: 'blur' }],
  exceptionQuantity: [{ required: true, message: '异常品数量不能为空', trigger: 'blur' }],
  description	: [{ required: true, message: '描述不能为空', trigger: 'blur' }],
})
const formRef = ref() // 表单 Ref
const partNumberFormRef =ref()//部件编号弹框Ref

//打开部件编号弹框
const openPartNumberForm = ()=>{
  // if(formData.dictExceptionRegistrationStatus==20 || viewStatus){
  //   return
  // }
  partNumberFormRef.value.open()
}

//getPartNumber
const getPartNumber=(arr)=>{
  formData.value.partNumber = arr[0].partNumber
  if(arr){
    arr.forEach(item=>{
      if(formData.value.partNumber==item.partNumber){
        formData.value.customerName=item.customerName
        formData.value.partUnit=item.partUnit
        formData.value.productNumber =item.productNumber
        formData.value.partName  =item.partName 
        formData.value.drawingNumber  =item.drawingNumber 
      }
    })
  }
}

// 只能填写数字，允许小数点后 2位数
const validateInput = () => {
  // 只允许数字和小数点
  formData.value.exceptionQuantity = formData.value.exceptionQuantity.replace(/[^0-9.]/g, ''); 
  const decimalParts =  formData.value.exceptionQuantity.split('.');
  if(decimalParts[0] == '')formData.value[val] = ''
  if (decimalParts.length > 2) {
  // 如果小数点出现多次，只保留第一个小数点之前的部分和小数点后的部分
  formData.value.exceptionQuantity = decimalParts[0] + '.' + decimalParts[1];
} else if (decimalParts[1] && decimalParts[1].length > 2) {
  // 如果小数部分超过2位，不允许继续输入
  formData.value.exceptionQuantity = decimalParts[0] + '.' + decimalParts[1].slice(0, 2);
}
};


/** 提交表单 */
const submitForm = async (type) => {
  // 校验表单
  if (!formRef) return
  const valid = await formRef.value.validate()
  if (!valid) return
  // 提交请求
  formLoading.value = true
  formData.value.exceptionQuantity = Number(formData.value.exceptionQuantity)
  try {
    //保存
    if(type=='save'){
      await MgmtDefectiveProductRegistrationApi.createMgmtDefectiveProductRegistration(formData.value)
      message.success(t('保存成功'))
      goBack()
      //提交
    }else if(type=='commit'){
      formData.value.id =Number(query.id)
      formData.value.dictExceptionRegistrationStatus = 20
      await MgmtDefectiveProductRegistrationApi.updateMgmtDefectiveProductRegistration(formData.value)
      message.success(t('提交成功'))
      goBack()
      //作废
    }else if(type=='cancel'){
      await MgmtDefectiveProductRegistrationApi.updateMgmtDefectiveProductRegistration({
        id:Number(query.id),
        dictExceptionRegistrationStatus:40
      })
      message.success(t('操作成功'))
      goBack()
      //撤回
    }else if(type=='withdraw'){
        if(formData.value.dictExceptionRegistrationStatus==20){
        await MgmtDefectiveProductRegistrationApi.updateMgmtDefectiveProductRegistration({
        id:Number(query.id),
        dictExceptionRegistrationStatus:10
      })
      message.success(t('操作成功'))
      goBack()
      }else{
        message.error(t('该数据已被检验'))
      }
    }
    dialogVisible.value = false
  } finally {
    formLoading.value = false
  }
}

/**返回 */
const tagsViewStore = useTagsViewStore()
const route = useRouter() // 路由
const goBack = async() => {
  //获取当前路由并删除tagView
  tagsViewStore.delView(route.currentRoute.value)
  //跳转列表页
  route.push({
    path:'/quality/quality/qualitycontrol/mgmtDefectiveProductRegistration'
    
  })
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
  dictInspectType:undefined,
  checkTaskNumber:undefined,
  productNumber:undefined,
  partNumber:undefined,
  partName:undefined,
  drawingNumber:undefined,
  exceptionQuantity:undefined,
  description:undefined,
  dictFinalConclusion:undefined,
  inspectionNotes:undefined
  }
  formRef.value?.resetFields()
}

const { query } = useRoute() // 路由的查询
const formHeight = ref(0)
/** 初始化 **/
const checkType =ref() //登录人检验类型
const viewStatus = ref(false) //查看状态
onMounted(async () => {
  const topBoxHeight = topBoxRef.value.clientHeight
  formHeight.value = document.body.clientHeight - 132 - topBoxHeight - 30
  formRef.value.$el.style.height= formHeight.value + 'px'
  formLoading.value = true
  await resetForm()
  try{if(query.id){
    formData.value = await MgmtDefectiveProductRegistrationApi.getMgmtDefectiveProductRegistration(query.id)
    console.log(formData.value,'formData.value')
  }
  if(query.type=='create'){
   const res = checkType.value = await MgmtDefectiveProductRegistrationApi.getCheckType()
   formData.value.dictInspectType =res.data
  }
  if(query.type=='view'){
    viewStatus.value = true
  }}
  finally{
    formLoading.value = false
  }

})
</script>

<style lang="scss" scoped>
.bg{
  background-color:white;
}
</style>
